package work.flow.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.state.State;
import work.flow.demo.entity.test01.LightEvent;
import work.flow.demo.entity.test01.LightState;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;

import java.util.EnumSet;

@Configuration
@EnableStateMachine
public class StateMachineConfig extends StateMachineConfigurerAdapter<LightState, LightEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<LightState, LightEvent> states) throws Exception {
        states.withStates()//
                .initial(LightState.OFF)  // 初始状态为OFF
                .states(EnumSet.allOf(LightState.class));//
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<LightState, LightEvent> transitions) throws Exception {
        transitions.withExternal()//
                .source(LightState.OFF)//
                .target(LightState.ON)//
                .event(LightEvent.TOGGLE)//
                .and()//
                .withExternal()//
                .source(LightState.ON)//
                .target(LightState.OFF)//
                .event(LightEvent.TOGGLE);
    }

    @Override
    public void configure(StateMachineConfigurationConfigurer<LightState, LightEvent> config) throws Exception {
        config.withConfiguration().autoStartup(true)  // 确保自动启动
                .listener(listener());
    }

    @Bean
    public StateMachineListener<LightState, LightEvent> listener() {
        return new StateMachineListenerAdapter<>() {
            @Override
            public void stateChanged(State<LightState, LightEvent> from, State<LightState, LightEvent> to) {
                System.out.println("State changed from " + (from == null ? "null" : from.getId()) + " to " + to.getId());
            }
        };
    }

}
